package com.example.blog.config;

import com.example.blog.enums.ResultEnums;
import com.example.blog.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * 捕获异常
 * @return 异常信息
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
    //这个方法是用来处理全部抛出的异常
    @ExceptionHandler
    public Result handler(Exception e){
        log.error("发现异常,e:{}",e.getMessage());
        return Result.fail(e.getMessage());
    }

    //捕获404
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    @ExceptionHandler
    public Result handler(NoResourceFoundException e){
        log.error("文件不存在,e:{}",e.getResourcePath());//获取的是发生异常的文件路径
        return Result.fail(ResultEnums.NOT_FIND.getCode(), e.getMessage());
    }

    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    @ExceptionHandler
    public Result handler(IllegalArgumentException e){
        log.error("参数为空,e:{}",e.getMessage());//获取的是发生异常的文件路径
        return Result.fail(ResultEnums.NULL_PARAM.getCode(), e.getMessage());
    }

}
